package ldh.serialize.type;

import java.io.IOException;

import ldh.serialize.BinarySerialized;
import ldh.serialize.io.ByteBuf;
import ldh.serialize.util.SerializedUtil;

public class ShortSerialized  implements BinarySerialized<Short> {

	@Override
	public void write(ByteBuf out, Short num) throws IOException {
		if (num == null) {
			SerializedUtil.writeByte(out, (byte) 0);
			return;
		}
		SerializedUtil.writeByte(out, (byte) 1);
		byte[] i32out = new byte[2];
	    i32out[0] = (byte)(0xff & (num >> 8));
	    i32out[1] = (byte)(0xff & (num));
	    out.writeBytes(i32out);
	}

	@Override
	public Short read(ByteBuf in) throws IOException {
		byte isNull = SerializedUtil.readByte(in);
		if (isNull < 1) {
			return null;
		}
		byte[] bytes = new byte[2];
		in.readBytes(bytes);
		return (short) (
        ((bytes[0] & 0xff) <<  8) |
        ((bytes[1] & 0xff))
        );
	}

	@Override
	public Class<Short> getClassType() {
		return Short.class;
	}
}
